﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cxuu.Web.Authorize
{
    public class LoginUtil
    {
        private readonly AdminUserService _adminUserService;
        private readonly AdminUserGroupService _adminUserGroupService;
        public LoginUtil(AdminUserService adminUserService, AdminUserGroupService adminUserGroupService)
        {
            _adminUserService = adminUserService;
            _adminUserGroupService = adminUserGroupService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user">登录的用户</param>
        /// <param name="remember"></param>
        public async Task SignInAsync(AdminUser user, bool remember)
        {
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.PrimarySid, user.Id.ToString()),
                    new Claim(ClaimTypes.PrimaryGroupSid, user.Gid.ToString()),
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim(ClaimTypes.UserData, JsonSerializer.Serialize(user))
                };

            await App.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(new ClaimsIdentity(claims, "CxuuPassport")),
                    new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddDays(7),
                        IsPersistent = remember,//在浏览器持久化，false的时候走session持久化
                        AllowRefresh = true//动态刷新令牌
                    }
             );
        }
        /// <summary>
        /// 登录用户ID
        /// </summary>
        /// <returns></returns>
        public async Task<int> LoginUserId()
        {
            var httpContext = App.HttpContext;
            if (httpContext == null)
                return 0;
            try
            {
                var result = await httpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (result.Succeeded)
                {
                    string idStr = result.Principal.FindFirst(ClaimTypes.PrimarySid).Value;
                    if (string.IsNullOrEmpty(idStr) || !int.TryParse(idStr, out int userId))
                        return 0;
                    else
                        return userId;
                }
            }
            catch { }
            return 0;
        }
        /// <summary>
        /// 登录用户角色ID
        /// </summary>
        /// <returns></returns>
        public int LoginGroupId()
        {
            return App.HttpContext.GetGId();
        }

        public UserAction UserAction()
        {
            var httpContext = App.HttpContext;
            if (httpContext == null)
                return null;

            UserAction userAction = new()
            {
                UserId = httpContext.GetUId(),
                Controller = httpContext.GetController(),
                Action = httpContext.GetAction(),
                Ip = httpContext.GetClientUserIp(),
            };
            return userAction;
        }

        public async Task<UserInfo> UserInfoAsync()
        {
            int userId = await LoginUserId();
            if (userId == 0)
            {
                return null;
            }
            ViewAdminUser adminUser = await _adminUserService.GetAsync(userId);
            AdminUserGroup adminUserGroup = await _adminUserGroupService.GetAsync(adminUser.Gid);
            UserInfo viewAdminUser = new()
            {
                UserId = userId,
                Gid = adminUser.Gid,
                DeptId = adminUser.DeptId,
                PostId = adminUser.PostId,
                PostName = adminUser.PostName,
                PostCode = adminUser.PostCode,
                DeptName = adminUser.DeptName,
                Username = adminUser.Username,
                Nickname = adminUser.Nickname,
                Status = adminUser.Status,
                Avatar = adminUser.Avatar,
                Phone = adminUser.Phone,
                Sex = adminUser.Sex,
                Groupname = adminUserGroup.Groupname,
            };

            try
            {
                viewAdminUser.SystemRole = JsonSerializer.Deserialize<List<string>>(adminUserGroup.Systemrole);
            }
            catch {}
            return viewAdminUser;
        }

        /// <summary>
        /// MVC 视图层判断显示权限
        /// </summary>
        /// <param name="permissionKey"></param>
        /// <returns></returns>
        public async Task<bool> AuthView(string permissionKey)
        {
            UserInfo viewAdminUser = await UserInfoAsync();
            if (viewAdminUser.Gid == 1)
                return true;
            return viewAdminUser.SystemRole.Exists(x => x == permissionKey);
        }

    }
}
